package leju.common.widget;

import java.util.Date;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.leju.common.R;
import com.leju.common.util.Utils;

public class PushRefreshListView extends ListView
		implements OnScrollListener {
	private final static int RELEASE_To_REFRESH = 0;
	private final static int PULL_To_REFRESH = 1;
	// 正在刷新
	private final static int REFRESHING = 2;
	// 刷新完成
	private final static int DONE = 3;
	private final static int LOADING = 4;

	private final static int RATIO = 3;

	private boolean isRecored;
	private int headContentWidth;
	private int headContentHeight;
	private int startY;
	private int firstItemIndex;
	private int state;
	private boolean isBack;
	private OnRefreshListener refreshListener;
	private boolean isRefreshable;
	
	private LinearLayout mRefreshViewContainer;
	private View mCustomRefreshView;
	private View mDefaultRefreshView;
	
	
	private LayoutInflater inflater;
	private TextView tipsTextview;
	private TextView lastUpdatedTextView;
	private ImageView arrowImageView;
	private ProgressBar progressBar;

	private RotateAnimation animation;
	private RotateAnimation reverseAnimation;

	int i = 1;

	public PushRefreshListView(Context context) {
		super(context, null);
		init(context);
	}

	public PushRefreshListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	private void init(Context context) {
		//setCacheColorHint(context.getResources().getColor(R.color.transparent));
		mRefreshViewContainer = new LinearLayout(context);
		addHeaderView(mRefreshViewContainer, null, false);
		setOnScrollListener(this);
		
		state = DONE;
		isRefreshable = false;
	}
	
	public void addCustomRefreshView(View view) {
		if ((mCustomRefreshView = view) != null) {
			mDefaultRefreshView = null;
			addRefreshViewToConstainer(mCustomRefreshView);
		}
	}
	
	public void setDefaultRefreshView(){
		mCustomRefreshView = null;
		mDefaultRefreshView = View.inflate(getContext(), R.layout.list_view_header_refresh_layout, null);
		arrowImageView = (ImageView) mDefaultRefreshView.findViewById(R.id.head_arrowImageView);
		arrowImageView.setMinimumWidth(70);
		arrowImageView.setMinimumHeight(50);
		progressBar = (ProgressBar) mDefaultRefreshView.findViewById(R.id.head_progressBar);
		tipsTextview = (TextView) mDefaultRefreshView.findViewById(R.id.head_tipsTextView);
		lastUpdatedTextView = (TextView) mDefaultRefreshView.findViewById(R.id.head_lastUpdatedTextView);

		animation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		animation.setInterpolator(new LinearInterpolator());
		animation.setDuration(250);
		animation.setFillAfter(true);

		reverseAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		reverseAnimation.setInterpolator(new LinearInterpolator());
		reverseAnimation.setDuration(200);
		reverseAnimation.setFillAfter(true);
		
		addRefreshViewToConstainer(mDefaultRefreshView);
	}
	
	private void addRefreshViewToConstainer(View view){
		if (view != null) {
			mRefreshViewContainer.removeAllViews();
			isRefreshable = true;
			mRefreshViewContainer.addView(view, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
			measureView(mRefreshViewContainer);
			headContentHeight = mRefreshViewContainer.getMeasuredHeight();
			headContentWidth = mRefreshViewContainer.getMeasuredWidth();
			log("width:" + headContentWidth + " height:" + headContentHeight);
			mRefreshViewContainer.setPadding(0, -1 * headContentHeight, 0, 0);
			mRefreshViewContainer.invalidate();
		}
	}
	
	//主动调用加载
	public void doRefresh(){
		state = REFRESHING;
		log("ACTION_UP RELEASE_To_REFRESH changeHeaderViewByState() " + "这是第  " + i++ + "步" + 3);
		mRefreshViewContainer.setPadding(0, 0, 0, 0);
		changeRefreshViewByState(RELEASE_To_REFRESH, REFRESHING);
		onRefresh();
		log("ACTION_UP RELEASE_To_REFRESH changeHeaderViewByState()" + " 这是第  " + i++ + "步" + 3);
	}

	public void onScroll(AbsListView arg0, int firstVisiableItem, int arg2, int arg3) {
		firstItemIndex = firstVisiableItem;
	}

	public void onScrollStateChanged(AbsListView arg0, int arg1) {
	}

	public boolean onTouchEvent(MotionEvent event) {
		if (isRefreshable) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				if (firstItemIndex == 0 && !isRecored) {
					isRecored = true;
					startY = (int) event.getY();
					log("ACTION_DOWN 这是第  " + i++ + "步" + 1);
				}
				break;
			case MotionEvent.ACTION_UP:
				if (state != REFRESHING && state != LOADING) {
					if (state == DONE) {
					}
					if (state == PULL_To_REFRESH) {
						state = DONE;
						log("ACTION_UP PULL_To_REFRESH and changeHeaderViewByState()" + " 这是第  " + i++ + "步前" + 2);
						mRefreshViewContainer.setPadding(0, -1 * headContentHeight, 0, 0);
						changeRefreshViewByState(PULL_To_REFRESH, DONE);
						log("ACTION_UP PULL_To_REFRESH and changeHeaderViewByState() " + "这是第  " + i++ + "步后" + 2);
					}
					if (state == RELEASE_To_REFRESH) {
						doRefresh();
					}
				}
				isRecored = false;
				isBack = false;
				break;
			case MotionEvent.ACTION_MOVE:
				int tempY = (int) event.getY();
				if (!isRecored && firstItemIndex == 0) {
					isRecored = true;
					startY = tempY;
					log("ACTION_MOVE 这是第  " + i++ + "步" + 4);
				}
				if (state != REFRESHING && isRecored && state != LOADING) {
					if (state == RELEASE_To_REFRESH) {
						setSelection(0);
						if (((tempY - startY) / RATIO < headContentHeight) && (tempY - startY) > 0) {
							state = PULL_To_REFRESH;
							changeRefreshViewByState(RELEASE_To_REFRESH, PULL_To_REFRESH);
							log("changeHeaderViewByState() 这是第  " + i++ + "步" + 5);
						} else if (tempY - startY <= 0) {
							state = DONE;
							mRefreshViewContainer.setPadding(0, -1 * headContentHeight, 0, 0);
							changeRefreshViewByState(RELEASE_To_REFRESH, DONE);
							log("ACTION_MOVE RELEASE_To_REFRESH 2  changeHeaderViewByState " + "这是第  " + i++ + "步" + 6);
						}
					}
					if (state == PULL_To_REFRESH) {
						setSelection(0);
						if ((tempY - startY) / RATIO >= headContentHeight) {
							state = RELEASE_To_REFRESH;
							isBack = true;
							log("changeHeaderViewByState " + "这是第  " + i++ + "步前" + 7);
							changeRefreshViewByState(PULL_To_REFRESH, RELEASE_To_REFRESH);
							log("changeHeaderViewByState " + "这是第  " + i++ + "步后" + 7);
						} else if (tempY - startY <= 0) {
							state = DONE;
							mRefreshViewContainer.setPadding(0, -1 * headContentHeight, 0, 0);
							changeRefreshViewByState(PULL_To_REFRESH, DONE);
							log("ACTION_MOVE changeHeaderViewByState PULL_To_REFRESH 2" + " 这是第  " + i++ + "步" + 8);
						}
					}
					if (state == DONE) {
						if (tempY - startY > 0) {
							state = PULL_To_REFRESH;
							log("ACTION_MOVE DONE changeHeaderViewByState " + "这是第  " + i++ + "步前" + 9);
							changeRefreshViewByState(DONE, PULL_To_REFRESH);
							log("ACTION_MOVE DONE changeHeaderViewByState " + "这是第  " + i++ + "步后" + 9);
						}
					}
					if (state == PULL_To_REFRESH) {
						mRefreshViewContainer.setPadding(0, -1 * headContentHeight + (tempY - startY) / RATIO, 0, 0);
						log(-1 * headContentHeight + (tempY - startY) / RATIO + "ACTION_MOVE PULL_To_REFRESH 3  这是第  " + i++ + "步" + 10);
					}
					if (state == RELEASE_To_REFRESH) {
						mRefreshViewContainer.setPadding(0, (tempY - startY) / RATIO	- headContentHeight, 0, 0);
						log("ACTION_MOVE PULL_To_REFRESH 4 这是第  " + i++ + "步" + 11);
					}
				}
				break;
			}
		}
		return super.onTouchEvent(event);
	}

	private void changeRefreshViewByState(int oldState, int newState) {
		if (refreshListener != null && mCustomRefreshView != null) {
			refreshListener.onRefreshStateChange(mCustomRefreshView, oldState, newState);
		}
		if (mDefaultRefreshView != null) {
			switch (newState) {
			case RELEASE_To_REFRESH:
				arrowImageView.setVisibility(View.VISIBLE);
				progressBar.setVisibility(View.GONE);
				tipsTextview.setVisibility(View.VISIBLE);
				//lastUpdatedTextView.setVisibility(View.VISIBLE);
				arrowImageView.clearAnimation();
				arrowImageView.startAnimation(animation);
				tipsTextview.setText("松手加载数据...");
				log("RELEASE_To_REFRESH 这是第  " + i++ + "步" + 12 + "请释放 刷新");
				break;
			case PULL_To_REFRESH:
				progressBar.setVisibility(View.GONE);
				tipsTextview.setVisibility(View.VISIBLE);
				//lastUpdatedTextView.setVisibility(View.VISIBLE);
				arrowImageView.clearAnimation();
				arrowImageView.setVisibility(View.VISIBLE);
				if (isBack) {
					isBack = false;
					arrowImageView.clearAnimation();
					arrowImageView.startAnimation(reverseAnimation);
				} 
				tipsTextview.setText("下拉加载数据!");
				log("PULL_To_REFRESH 这是第  " + i++ + "步" + 13 + "  changeHeaderViewByState()");
				break;
			case REFRESHING:
				progressBar.setVisibility(View.VISIBLE);
				arrowImageView.clearAnimation();
				arrowImageView.setVisibility(View.GONE);
				tipsTextview.setText("LEJU正努力工作，请稍等...");
				//lastUpdatedTextView.setVisibility(View.VISIBLE);
				log("REFRESHING 这是第  " + i++ + "步" + "正在加载中 ...REFRESHING");
				break;
			case DONE:
				progressBar.setVisibility(View.GONE);
				arrowImageView.clearAnimation();
				//arrowImageView.setImageResource(R.drawable.refresh_arrow);
				tipsTextview.setText("数据加载完毕! ");
				//lastUpdatedTextView.setVisibility(View.VISIBLE);
				log("DONE 这是第  " + i++ + "步" + "已经加载完毕- DONE ");
				break;
			}
		}
	}

	public void setonRefreshListener(OnRefreshListener refreshListener) {
		this.refreshListener = refreshListener;
		isRefreshable = true;
	}

	public interface OnRefreshListener {
		public void onRefreshing();
		public void onRefreshStateChange(View refreshView, int oldState, int newState);
	}

	public void onRefreshComplete() {
		state = DONE;
		if (mDefaultRefreshView != null) {			
			//lastUpdatedTextView.setText("已加载完成: " + new Date().toLocaleString());
		}
		mRefreshViewContainer.setPadding(0, -1 * headContentHeight, 0, 0);
		changeRefreshViewByState(PULL_To_REFRESH, DONE);
		log("onRefreshComplete() 被调用。。。");
	}
	
	private void log(String msg) {
		Utils.log(msg);
	}

	private void onRefresh() {
		if (refreshListener != null) {
			refreshListener.onRefreshing();
			log("onRefresh被调用，这是第  " + i++ + "步");
		}
	}

	private void measureView(View child) {
		ViewGroup.LayoutParams p = child.getLayoutParams();
		if (p == null) {
			p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
		}
		int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
		int lpHeight = p.height;
		int childHeightSpec;
		if (lpHeight > 0) {
			childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
		} else {
			childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
		}
		child.measure(childWidthSpec, childHeightSpec);
	}

	public void setAdapter(BaseAdapter adapter) {
		//lastUpdatedTextView.setText("this is in MyListView:" + new Date().toLocaleString());
		super.setAdapter(adapter);
	}

}
